﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace EnergyMonitorWs
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class EnergyMonWs
    {

        [OperationContract]
        [WebInvoke(Method="GET",UriTemplate="set?energy={energy}&temp={temp}&date={date}&time={time}")]
        public void SetCurrentValues(string energy, string temp, string date, string time)
        {
            Cache cache = HttpRuntime.Cache;

            try
            {
                cache.Remove("energy");
                cache.Remove("temp");
                cache.Remove("date");
                cache.Remove("time");
            }
            catch { }

            cache.Add("energy", energy, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            cache.Add("temp", temp, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            cache.Add("date", date, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            cache.Add("time", time, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

            return;
        }

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "xml/{value}")]
        public string GetValueXml(string value)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            return GetValue(value.ToLower());
        }
        
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "json/{value}", ResponseFormat = WebMessageFormat.Json)]
        public string GetValueJson(string value)
        {
            return GetValue(value.ToLower());
        }

        private string GetValue(string key)
        {
            Cache cache = HttpRuntime.Cache;

            string retVal = (string)cache.Get(key);
            if (null == retVal)
            {
                retVal = "N/A";
            }

            return retVal;
        }
    }
    
}
